package cn.com.utt.common.service.impl;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.alibaba.fastjson.JSON;
import cn.com.utt.common.mapper.ResourceMapper;
import cn.com.utt.common.mapper.RoleMapper;
import cn.com.utt.common.mapper.UserMapper;
import cn.com.utt.common.mapper.UserRoleMapper;
import cn.com.utt.common.service.RoleService;
import cn.com.utt.common.vo.Res;
import cn.com.utt.common.vo.Resource;
import cn.com.utt.common.vo.Role;
import cn.com.utt.common.vo.User;

@Service("roleService")
public class RoleServiceImpl implements RoleService {
	
	@Autowired
	private RoleMapper roleMapper;
	
	@Autowired
	private UserMapper userMapper;
	
	@Autowired
	private ResourceMapper resourceMapper;
	
	@Autowired
	private UserRoleMapper userRoleMapper;

	@Override
	public List<Role> queryAll() {
		return roleMapper.queryAll();
	}
	
	@Override
	public List<Role> queryRoleList(User user,Long childrenId,Long type) {
		List<Role> roles = roleMapper.query();
		// type 1 新增 2 编辑
//		Long id;
//		if(type == 1){
//			id = user.getId();
//		}else{
//			User children = userMapper.queryById(childrenId);
//			id = children.getParentId();
//		}
//		List<Role> auths = userRoleMapper.queryByUid(id);
//		roles.retainAll(auths);
		return roles;
	}

	@Override
	public List<Role> queryBasic() {
		return roleMapper.queryBasic();
	}

	@Override
	public Map<String, Object> queryMenu(Long userId,String resourceTableName, String roleResourceTableName) {
		List<Res> url = new ArrayList<>();
		Map<String, List<Res>> urlList = new HashMap<>();
		List<Resource> first = resourceMapper.queryFirstMenu(userId,resourceTableName, roleResourceTableName);
		for (Resource resource : first) {
			Res res = new Res();
			res.setId(resource.getName());
			res.setName(resource.getDescr());
			res.setLocal("home_"+resource.getName());
			url.add(res);
			
			List<Resource> second = resourceMapper.querySecondMenu(userId,resource,resourceTableName, roleResourceTableName);
			if(second != null && !second.isEmpty()){
				List<Res> temp = new ArrayList<>();
				for (Resource resource1 : second) {
					Res res1 = new Res();
					res1.setId(resource1.getName());
					res1.setName(resource1.getDescr());
					res1.setLocal(resource1.getName());
					temp.add(res1);
				}
				urlList.put(resource.getName(), temp);
			}else{
				if(resource.getName().equals("home")){
					urlList.put(resource.getName(), new ArrayList<>());
				}else{
					url.remove(url.size()-1);
				}
			}
		}
		Map<String, Object> result = new HashMap<>();
		result.put("url", url);
		result.put("urlList", urlList);
		System.out.println(JSON.toJSONString(url));
		System.out.println(JSON.toJSONString(urlList));
		return result;
	}

}
